package com.yxcz.daoImpl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;

import org.springframework.stereotype.Repository;
import com.yxcz.dao.CommonDAO;

@Repository
public class CommonDAOImpl<T, PK extends Serializable> implements CommonDAO<T, PK> {
	@PersistenceContext
	private  EntityManager entityManager; 

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}



	private Class<T> entityClass;


	@SuppressWarnings("unchecked")
	public CommonDAOImpl() {
		this.entityClass = null;  
        Class<T> c = (Class<T>) getClass();  
        Type t = c.getGenericSuperclass();  
        if (t instanceof ParameterizedType) {  
            Type[] p = ((ParameterizedType) t).getActualTypeArguments();  
            this.entityClass = (Class<T>) p[0];  
        }
	}


	public void add(T entity) throws Exception{
		// TODO Auto-generated method stub
		entityManager.persist(entity);
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<T> list(){
		
		return (ArrayList<T>) this.entityManager.createQuery("from " + this.entityClass.getName()).getResultList();
	}

	@Override
	public T find(PK id) {
		// TODO Auto-generated method stub
		return this.entityManager.find(this.entityClass,id);
	}

	@Override
	public void delete(T entity){
		this.entityManager.remove(this.entityManager.merge(entity));
		
	}

	@Override
	public void save(T entity) {
		
		this.entityManager.merge(entity);
		
	}

	
	
	@Override
	public List query(String sql, HashMap<String,Object> vars) {
		// TODO Auto-generated method stub
		Query query = this.entityManager.createQuery(sql);
		for (String var : vars.keySet()) {
			query.setParameter(var,vars.get(var));
		}
		return query.getResultList();
		
	}



}
